package androidx.blogger.activities;

import com.google.gwt.user.client.rpc.AsyncCallback;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import androidx.blogger.BloggerApplication;
import androidx.blogger.Log;
import androidx.blogger.R;
import androidx.blogger.tasks.DeleteBlogEntryTask;
import androidx.gdata.blogger.BlogEntry;

public class ViewBlogPost extends ConnectedActivity {
	private TextView entryContentEditText;
	private Button editButton;
	
  private static final int MENU_EDIT = Menu.FIRST;
  private static final int MENU_DELETE = Menu.FIRST + 1;

	@Override
	protected void onCreate2(Bundle savedInstanceState) {
		setContentView(R.layout.view_post);
		entryContentEditText = (TextView) findViewById(R.id.contentEditText);
		editButton = (Button) findViewById(R.id.postButton);
		BlogEntry post = BloggerApplication.getInstance().getCurrentPost();
		entryContentEditText.setText(post.getContent().getData());
		setTitle(post.getTitle());
		editButton.setOnClickListener(editButtonClicked);
	}

	OnClickListener editButtonClicked = new OnClickListener() {
		public void onClick(View arg0) {
			onEditBlogPost();
		}
	};
	
	private void onEditBlogPost() {
		Intent intent = new Intent(this, EditBlogPost.class);
		startActivity(intent);
		finish();
	}
	
	private void onDeleteBlogPost(BlogEntry post) {
    Log.i("Blog post '" + post.getTitle() + "' chosen for deletion");
    DeleteBlogEntryTask.execute(getProgressIndicator(""), post, blogDeleteCallback);
	}

  private void onBlogPostDeleted(BlogEntry deletedpost) {
  	Log.i("Post '" + deletedpost.getTitle() + "' has been deleted");
    BloggerApplication.getInstance().setCurrentPost(null);
    BloggerApplication.getInstance().setBlogEntryCollection(null);
    finish();
  }
	
  private AsyncCallback<BlogEntry> blogDeleteCallback = new AsyncCallback<BlogEntry>() {
    public void onSuccess(BlogEntry result) {
      onBlogPostDeleted(result);
    }

    public void onFailure(Throwable t) {
    	longMessage("Error deleting blog post");
    }
  };
	
	
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);      
    menu.add(Menu.NONE, MENU_EDIT, Menu.NONE, "Edit Post").setIcon(android.R.drawable.ic_menu_edit);
    menu.add(Menu.NONE, MENU_DELETE, Menu.NONE, "Delete Post").setIcon(android.R.drawable.ic_menu_delete);
    return true;
  }
  
  /** Process the options menu item selection */
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
      case MENU_EDIT: 
        onEditBlogPost();
        return true;
      case MENU_DELETE: 
      	onDeleteBlogPost(BloggerApplication.getInstance().getCurrentPost());
        return true;
    }
    return false;
  }

	
}
